package com.admin.logging.rest;

import com.admin.common.utils.PageResult;
import com.admin.component.web.MultipartFileUtil;
import com.admin.logging.annotation.Log;
import com.admin.logging.dto.SysLogQueryDTO;
import com.admin.logging.entity.SysLog;
import com.admin.logging.enums.LogTypeEnum;
import com.admin.logging.enums.OperateTypeEnum;
import com.admin.logging.service.SysLogService;
import com.admin.oauth.util.LoginUserUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author sq-lan
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/logs")
@Api(tags = "系统：日志管理")
public class SysLogController {

    private final SysLogService sysLogService;

    @GetMapping
    @ApiOperation("日志查询")
    @PreAuthorize("@ss.check()")
    public ResponseEntity<PageResult<SysLog>> info(SysLogQueryDTO dto) {
        dto.setLogType(LogTypeEnum.INFO.getValue());
        return new ResponseEntity<>(sysLogService.paging(dto), HttpStatus.OK);
    }

    @GetMapping(value = "/warning")
    @ApiOperation("日志查询警告")
    @PreAuthorize("@ss.check()")
    public ResponseEntity<PageResult<SysLog>> warning(SysLogQueryDTO dto) {
        dto.setLogType(LogTypeEnum.WARNING.getValue());
        return new ResponseEntity<>(sysLogService.paging(dto), HttpStatus.OK);
    }

    @GetMapping(value = "/error")
    @ApiOperation("日志查询错误")
    @PreAuthorize("@ss.check()")
    public ResponseEntity<PageResult<SysLog>> error(SysLogQueryDTO dto) {
        dto.setLogType(LogTypeEnum.ERROR.getValue());
        return new ResponseEntity<>(sysLogService.paging(dto), HttpStatus.OK);
    }

    @GetMapping(value = "/user")
    @ApiOperation("用户日志查询")
    public ResponseEntity<PageResult<SysLog>> listUser(SysLogQueryDTO dto) {
        dto.setLogType(LogTypeEnum.INFO.getValue());
        dto.setUsername(LoginUserUtil.userName());
        return new ResponseEntity<>(sysLogService.paging(dto), HttpStatus.OK);
    }

    @GetMapping(value = "/error/{id}")
    @ApiOperation("日志异常详情查询")
    @PreAuthorize("@ss.check()")
    public ResponseEntity<Object> logDetail(@PathVariable int id) {
        return new ResponseEntity<>(sysLogService.exceptionDetail(id), HttpStatus.OK);
    }

    @DeleteMapping(value = "/del/error")
    @Log(module = "日志管理", operateType = OperateTypeEnum.REMOVE, description = "删除所有ERROR日志")
    @ApiOperation("删除所有ERROR日志")
    @PreAuthorize("@ss.check()")
    public ResponseEntity<Object> delError() {
        sysLogService.remove(Wrappers.<SysLog>lambdaQuery().eq(SysLog::getLogType, LogTypeEnum.ERROR.getValue()));
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @DeleteMapping(value = "/del/info")
    @Log(module = "日志管理", operateType = OperateTypeEnum.REMOVE, description = "删除所有INFO日志")
    @ApiOperation("删除所有INFO日志")
    @PreAuthorize("@ss.check()")
    public ResponseEntity<Object> delInfo() {
        sysLogService.remove(Wrappers.<SysLog>lambdaQuery().eq(SysLog::getLogType, LogTypeEnum.INFO.getValue()));
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@ss.check()")
    public void exportLog(HttpServletResponse response, SysLogQueryDTO dto) throws IOException {
        dto.setLogType(LogTypeEnum.INFO.getValue());
        MultipartFileUtil.downloadExcel(export(sysLogService.list(dto)), response);
    }

    @ApiOperation("导出错误数据")
    @GetMapping(value = "/error/download")
    @PreAuthorize("@ss.check()")
    public void exportErrorLog(HttpServletResponse response, SysLogQueryDTO dto) throws IOException {
        dto.setLogType(LogTypeEnum.WARNING.getValue());
        MultipartFileUtil.downloadExcel(export(sysLogService.list(dto)), response);
    }

    @GetMapping(value = "/operateTypeEnum")
    public ResponseEntity<Object> operateTypeEnum() {
        OperateTypeEnum[] values = OperateTypeEnum.values();
        JSONObject jsonObject = new JSONObject();
        for (OperateTypeEnum anEnum : values) {
            jsonObject.put(String.valueOf(anEnum.getCode()), anEnum.getLabel());
        }
        return new ResponseEntity<>(jsonObject, HttpStatus.OK);
    }

    public List<Map<String, Object>> export(List<SysLog> sysLogs) {
        List<Map<String, Object>> list = new ArrayList<>();
        for (SysLog sysLog : sysLogs) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("操作人", sysLog.getUsername());
            map.put("IP", sysLog.getRequestIp());
            map.put("IP来源", sysLog.getAddress());
            map.put("描述", sysLog.getDescription());
            map.put("浏览器", sysLog.getBrowser());
            map.put("请求耗时(毫秒)", sysLog.getTime());
            map.put("操作日期", sysLog.getCreateTime());
            list.add(map);
        }
        return list;
    }
}
